import { useState, forwardRef, useImperativeHandle, lazy } from "react";

import { Modal, Form, Input, message, Select, Tree } from "antd";

import { UpdatedUserInfoService } from "@/service";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { fetchGetUserListThunk, fetchUserDetail, IStore } from "@/store";
import { ThunkDispatch } from "@reduxjs/toolkit";
import { RegisterUserService } from "@/service";
export interface IProps {
  operate: {
    title: string;
    edit: boolean;
  };
  Tree?: any[];
}
const UserModal = forwardRef((props: IProps, ref) => {
  // rtk
  const dispatch = useDispatch<ThunkDispatch<any, any, any>>();
  const userStore = useSelector((state: IStore) => state.user, shallowEqual);
  // Modal
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [currentData, setCurrentData] = useState<any>({});
  const [backData, setBackData] = useState<any>({});

  // 表单验证
  const [form] = Form.useForm();
  const showModal = (item?: any) => {
    form.setFieldsValue(item);
    setBackData(item);
    setCurrentData(item);
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    form.resetFields();
    setIsModalOpen(false);
  };
  const handleOk = () => {
    form.submit();
  };
  useImperativeHandle(ref, () => {
    return {
      showModal,
    };
  });
  const onFinish = async (rules: any) => {
    let res: any;
    const department = userStore.department.find(
      (item) => item.name == currentData.department
    );
    if (props.operate.edit) {
      if (backData.department == "") {
        currentData.permissions = [
          ...new Set([
            ...backData.permissions.split(","),
            ...department.permissions.split(","),
          ]),
        ].join(",");
        res = await UpdatedUserInfoService(currentData);
      } else if (currentData.department != backData.department) {
        const oldDepartment = userStore.department.find(
          (item) => item.name == backData.department
        );
        const data = backData.permissions
          .split(",")
          .filter(
            (item) => !oldDepartment.permissions.split(",").includes(item)
          );
        currentData.permissions = [
          ...new Set([...data, ...department.permissions.split(",")]),
        ].join(",");
      }
      res = await UpdatedUserInfoService(currentData);
    } else {
      // 找到部门的权限
      currentData.permissions =
        department.permissions ?? [];
      res = await RegisterUserService(currentData);
    }
    if (res.code === 0) {
      dispatch(fetchGetUserListThunk());
      dispatch(fetchUserDetail(userStore.user.id));
      form.resetFields();
      message.success(res.msg);
      setIsModalOpen(false);
    } else {
      message.error(res.msg);
    }
  };
  const onFinishFailed = (errorInfo: any) => {
    message.error("请按照格式填写");
  };

  return (
    <Modal
      destroyOnClose
      title={props.operate.title}
      open={isModalOpen}
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <Form
        labelCol={{ span: 4 }}
        form={form}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
      >
        <Form.Item label="昵称" name="nick_name">
          <Input
            placeholder="请输入昵称"
            onInput={(event: any) =>
              setCurrentData({
                ...currentData,
                nick_name: event.target.value,
              })
            }
            value={currentData["nick_name"]}
          ></Input>
        </Form.Item>

        <Form.Item
          label="真实姓名"
          name="user_name"
          rules={[
            { required: true, message: "姓名不能为空" },
            { pattern: /^.{2,}/, message: "姓名不能少于2个" },
          ]}
        >
          <Input
            placeholder="请输入真实姓名"
            onInput={(event: any) =>
              setCurrentData({
                ...currentData,
                user_name: event.target.value,
              })
            }
            value={currentData["user_name"]}
          ></Input>
        </Form.Item>
        <Form.Item
          label="性别"
          name="sex"
          rules={[{ required: true, message: "性别不能为空" }]}
        >
          <Select
            placeholder="请输入性别"
            onChange={(val) => setCurrentData({ ...currentData, sex: val })}
            options={[
              {
                label: "男",
                value: "男",
              },
              {
                label: "女",
                value: "女",
              },
            ]}
            value={currentData["sex"]}
          ></Select>
        </Form.Item>
        <Form.Item
          label="手机号码"
          name="phone"
          rules={[
            { required: true, message: "手机号码不能为空" },
            { pattern: /^1[3-9]\d{9}$/, message: "请填写正确的11位手机号码" },
          ]}
        >
          <Input
            placeholder="请输入手机号码"
            onInput={(event: any) =>
              setCurrentData({ ...currentData, phone: event.target.value })
            }
            value={currentData["phone"]}
          ></Input>
        </Form.Item>
        <Form.Item
          label="部门"
          name="department"
          rules={[{ required: true, message: "部门不能为空" }]}
        >
          <Select
            placeholder="请输入部门"
            value={currentData["department"]}
            onChange={(val) =>
              setCurrentData({ ...currentData, department: val })
            }
            options={userStore.department.map((item) => ({
              label: item.name,
              value: item.name,
            }))}
          ></Select>
        </Form.Item>
        <Form.Item
          label="邮箱"
          name="email"
          rules={[
            { required: true, message: "邮箱不能为空" },
            {
              pattern: /^[\w.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
              message: "请填写正确邮箱",
            },
          ]}
        >
          <Input
            value={currentData["email"]}
            placeholder="请输入邮箱"
            onInput={(event: any) =>
              setCurrentData({ ...currentData, email: event.target.value })
            }
          ></Input>
        </Form.Item>
        <Form.Item name="mail_is_allowed" label="邮件接受">
          <Select
            onChange={(val) =>
              setCurrentData({ ...currentData, mail_is_allowed: val })
            }
            placeholder="是否接收库存邮件的发送"
            options={[
              {
                label: "接受邮件",
                value: true,
              },
              {
                label: "不收邮件",
                value: false,
              },
            ]}
          ></Select>
        </Form.Item>
        <Form.Item name="status" label="登录授权">
          <Select
            onChange={(val) => setCurrentData({ ...currentData, status: val })}
            placeholder="是否能登陆系统"
            options={[
              {
                label: "给予登录",
                value: true,
              },
              {
                label: "不予登录",
                value: false,
              },
            ]}
          ></Select>
        </Form.Item>
        <Form.Item label="描述" name="description">
          <Input.TextArea
            value={currentData["description"]}
            placeholder="请输入描述"
            onInput={(event: any) =>
              setCurrentData({
                ...currentData,
                description: event.target.value,
              })
            }
          ></Input.TextArea>
        </Form.Item>
      </Form>
    </Modal>
  );
});
export default UserModal;
